package com.example.backend;

import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.bind.annotation.RequestBody;
import com.fasterxml.jackson.databind.JsonNode;

@RestController
@CrossOrigin(origins = "*")
public class DatabaseSetup {

    @Autowired
    private UserService userService;

    @Autowired
    @Qualifier("gameMessageJdbcTemplate")  // 使用game_message数据库的JdbcTemplate
    private JdbcTemplate gameMessageJdbcTemplate;

    @Autowired
    @Qualifier("messageJdbcTemplate")  // 使用message数据库的JdbcTemplate
    private JdbcTemplate messageJdbcTemplate;

    @PostMapping("/getlocalmessage")
    public ResponseEntity<JsonNode> saveGameData(@RequestBody JsonNode requestData) {
        String username = requestData.get("username").asText();
        String gametime = requestData.get("gametime").asText();
        String clearancestatus = requestData.get("clearancestatus").asText();
        String clearancetime = requestData.get("clearancetime").asText();
        String[] weapons = requestData.get("weapons").asText().split(",");

        System.out.println(username + " " + gametime + " " + clearancestatus + " " + clearancetime);

        // 检查用户是否存在（使用message数据库）
        if (!userService.isUserExists(username)) {
            JsonNode response = JsonNodeFactory.instance.objectNode()
                    .put("success", "false")
                    .put("msg", "用户不存在");
            return ResponseEntity.status(404).body(response);
        }

        // 检查用户名是否在localmessage表格中
        String checkUserSQL = "SELECT COUNT(*) FROM localmessage WHERE username = ?";
        Integer count = gameMessageJdbcTemplate.queryForObject(checkUserSQL, Integer.class, username);

        // 根据是否存在来决定更新或插入
        String resultMsg = "";
        try {
            if (count > 0) {
                // 用户已存在，更新数据
                String updateSQL = "UPDATE localmessage SET weapon_names = ?, gametime = ?, clearancestatus = ?, clearancetime = ? WHERE username = ?";
                gameMessageJdbcTemplate.update(updateSQL, String.join(",", weapons), gametime, clearancestatus, clearancetime, username);
                resultMsg = "数据已更新";
            } else {
                // 用户不存在，插入数据
                String insertSQL = "INSERT INTO localmessage (username, weapon_names, gametime, clearancestatus, clearancetime) "
                        + "VALUES (?, ?, ?, ?, ?)";
                gameMessageJdbcTemplate.update(insertSQL, username, String.join(",", weapons), gametime, clearancestatus, clearancetime);
                resultMsg = "数据已保存";
            }
            JsonNode response = JsonNodeFactory.instance.objectNode()
                    .put("success", "true")
                    .put("msg", resultMsg);
            return ResponseEntity.ok(response);
        } catch (HttpClientErrorException e) {
            JsonNode response = JsonNodeFactory.instance.objectNode()
                    .put("success", "false")
                    .put("msg", "数据库操作失败");
            return ResponseEntity.status(500).body(response);
        }
    }
}
